<template>
	<view class="content">
		<text class="title">点击头像以切换用户</text>
		<view class="item" v-for="(item, index) in serviceList" :key="index" @click="cutUser(item.userId)">
			<view class="itemL">
				<image class="headImg" :src="item.headshot"></image>
				<text class="phone">{{ item.neckName }}</text>
			</view>
			<image v-if="item.userId == currentUserId" class="delImg" :src="staticUrl + '/image/mine/membermanage/currentUser.png'"></image>
		</view>
	</view>
</template>

<script>
const app = getApp();
import * as api from '@/api/login';
export default {
	data() {
		return {
			staticUrl:this.$config.StaticUrl,
			currentUserId: '', //当前登录用户的userId
			userInfo: {}, //已经登录的(存在缓存和store中的)用户列表
			serviceList: [], //已绑定的服务账户信息列表
			cutUserPhone: ''
		};
	},
	onLoad() {
		this.userInfo = this.$store.state.userInfo;
		this.currentUserId = this.$store.state.userInfo.currentUser.userId;
		console.log('Store中的内容：：', this.$store.state.userInfo);
		console.log('缓存中的内容：：', uni.getStorageSync('userInfo'));
		this.getServiceUserList();
	},
	methods: {
		// 获取服务账户绑定的用户信息
		getServiceUserList() {
			let userId = this.currentUserId;
			let that = this;
			let data = {
				userId: userId,
				action: 'getServiceUserList'
			};
			api.getServiceUserList(data)
				.then(function(res) {
					// console.log('getServiceUserList res',res);
					if (res.data.code == 2000) {
						that.serviceList = res.data.data.serviceUserList;
					}
				})
				.catch(function(error) {
					console.log('getServiceUserList fail', error);
				});
		},
		// 切换用户登录 首次切换需要跳转到登录界面
		cutUser(userId) {
			let that = this;
			console.log('切换用户' + userId);
			if (userId == this.currentUserId) {
				that.$toast('已是登录状态', { icon: 'error', duration: 1000 });
				return;
			}
			let loginListUserId = [];
			let cutUserInfo = {};
			// 遍历缓存中的用户信息
			this.userInfo.loginUserList.forEach(item => {
				loginListUserId.push(item.userId);
				if (userId == item.userId) {
					cutUserInfo = item;
				}
			});
			console.log(cutUserInfo);
			// 从服务列表中获取手机号
			this.serviceList.forEach(item => {
				if (userId == item.userId) {
					this.cutUserPhone = item.phone;
				}
			});
			// console.log(item.phone);
			// 判断要切换的账户是否已经存在了本地缓存
			if (loginListUserId.includes(userId)) {
				// 写入缓存
				try {
					const value = uni.getStorageSync('userInfo');
					if (value) {
						value.currentUser = cutUserInfo;
						console.log(value);
						uni.setStorageSync('userInfo', value);
						// 将需要切换用户的个人信息同步到现有的currentUser中去
						this.$store.commit('updateCurrentUser', cutUserInfo);
					}
				} catch (e) {
					// error
					console.log('error', e);
				}
				// 请求appsecret  判断是否过期
				that.updateSecret(cutUserInfo);
			} else {
				// 要切换的用户是新用户，不存在本地缓存中 此时，调用子用户登录的接口 ，避免重复调用短信api
				that.slaveUserLogin();
			}
		},
		// 子用户登录
		slaveUserLogin() {
			console.log('子用户登录');
			let that = this;
			let data = {
				userId: that.currentUserId,
				action: 'slaveUserLogin',
				params: that.cutUserPhone
			};
			api.slaveUserLogin(data).then(function(res) {
					console.log(res);
					if (res.data.code == 2000) {
						// 更新本地缓存和store的内容
						let appId = res.data.data.appIdInfo.appId;
						let appSecret = res.data.data.appIdInfo.appSecret;
						let userId = res.data.data.appIdInfo.userId;
						let userInfo = uni.getStorageSync('userInfo');
						// add new User
						userInfo.currentUser= {
								userId:userId,
								appId:appId,
								appSecret:appSecret,
								phone:that.cutUserPhone
						};
						let isNewUser = true;
						userInfo.loginUserList.forEach(item =>{
							if(item.userId == userId){
								item.appId = appId;
								item.appSecret = appSecret;
								item.phone = that.cutUserPhone;
								isNewUser = false;
							}
						});
						if(isNewUser){
							userInfo.loginUserList.push(userInfo.currentUser);
						};
						try{
							uni.setStorageSync('userInfo',userInfo);
							that.$store.commit('userInfo', userInfo);
						}catch(e){
							//TODO handle the exception
							console.log('缓存失败',e);
						}
						// 关闭蓝牙
						if (that.$store.state.isConnected) app.closeBluetoothAdapter();
						//刷新程序
						uni.reLaunch({
							url: '../../index/index',
							success() {
								app.globalData.isDeteDeviceState = false
								console.log('123relaunch success');
							}
						});
						
					} else {
						// 进入登录页面,走登录
						uni.navigateTo({
							url: 'reLogin/reLogin?phone=' + that.cutUserPhone
						});
					}
				})
				.catch(function(error) {
					console.log('slaveUserLogin fail', error);
				});
		},
		updateSecret(cutUserInfo) {
			let that = this;
			// 将这些信息
			let data = {
				userId: cutUserInfo.userId,
				action: 'updateAppSecret',
				params: {
					appId: cutUserInfo.appId,
					appSecret: cutUserInfo.appSecret,
					uuid: that.$store.state.deviceUUID
				}
			};
			//每次打开时更新appSecret  /service-sso/updateAppSecret
			api.updateAppSecret(data)
				.then(function(res) {
					console.log('updateAppSecret success', res);
					if (res.data.code == 2000) {
						//更新
						try {
							that.$store.commit('UpdateAppSecret', res.data.data.appSecret);
						} catch (e) {
							// error
							console.log('error', e);
						}
						console.log(that.$store.state.userInfo);
						// 关闭蓝牙
						if (that.$store.state.isConnected) app.closeBluetoothAdapter();
						// //刷新程序
						uni.reLaunch({
							url: '../../index/index',
							success() {
								app.globalData.isDeteDeviceState = false
								console.log('relaunch success');
							}
						});
					} else {
						uni.showToast({
							title: 'AppSecret已过期,请重新登录',
							icon: 'none'
						});
						let T = setTimeout(function() {
							clearTimeout(T);
							uni.navigateTo({
								url: 'reLogin/reLogin?phone=' + that.cutUserPhone
							});
						}, 2000);
					}
				})
				.catch(function(error) {
					console.log('updateAppSecret fail', error);
				});
		}
	}
};
</script>

<style>
page {
	background-color: #fafafa;
}
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.item {
	margin-top: 40rpx;
	width: 700rpx;
	height: 160rpx;
	background-color: #ffffff;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.itemL {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-left: 90rpx;
}
.headImg {
	width: 100rpx;
	height: 100rpx;
}
.delImg {
	width: 130rpx;
	height: 52rpx;
}
.phone {
	margin-left: 38rpx;
	font-size: 38rpx;
	font-family: Roboto;
	font-weight: bold;
	color: #333333;
}
.title {
	margin-bottom: 60rpx;
	margin-top: 80rpx;
	font-size: 44rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #333333;
}
</style>
